<?php

namespace App\Services\YunXinCloud;


use App\Actions\MessageAction;
use App\Dao\ClosenessDao;
use App\Dao\Mongodb\UserChatV2Dao;
use App\Dao\OnlineDao;
use App\Dao\UserDao;
use App\Dao\UserGagDao;
use App\Model\AnchorVideo;
use App\Model\Order;
use App\Model\User;
use App\Services\PushMessageService;
use App\Utils\LoggerUtil;
use App\Utils\MemcacheClient;
use App\Utils\MongoDBClient;
use App\Utils\RedisClient;
use Hyperf\Di\Annotation\Inject;

class WyyClientService
{

    #[Inject]
    public WyyClient $client;


    /**
     * 音视频2.0 Token鉴权
     * @param  $uid //用户id
     * @param  $call_id //绑定的房间名称
     * @param int $expireAt //Token 的过期时间，过期后，该用户将无法通过此 Token 加入房间
     * @return mixed|string
     */
    public function getTokenYunXin($uid, $call_id, int $expireAt = 600)
    {
        return $this->client->getTokenYunXin($uid, $call_id, $expireAt);
    }


    /**
     * 响应 Json
     * @param int $errCode
     * @param int $responseCode
     * @param string $callbackExt
     * @param array $modifyResponse
     * @return false|string
     */
    public function responseJson(int $errCode, int $responseCode, string $callbackExt = "", array $modifyResponse = [])
    {
        return json_encode(compact("errCode", "responseCode", "callbackExt", "modifyResponse"));
    }


    /**
     * 验证 CheckSum
     * @param $MD5
     * @param $CurTime
     * @param $CheckSum
     * @return bool
     */
    public function verifyCheckSum($MD5, $CurTime, $CheckSum)
    {
        return $this->client->verifyCheckSum($MD5, $CurTime, $CheckSum);
    }


    /**
     * 生成token
     * @param $uid
     * @return string
     */
    public function genToken($uid)
    {
        return $this->client->genToken($uid);
    }

    /**
     * 创建网易云信IM账号
     * @param $uid [会员id]
     * @return array
     */
    public function createUser($uid)
    {
        return $this->client->createUser($uid);
    }

    /**
     * 重置网易云信IM token
     * @param $uid [会员id]
     * @return array
     */
    public function refreshUser($uid)
    {
        return $this->client->refreshUser($uid);
    }

    /**
     * 更新用户名片
     * @param $uid [uid]
     * @param $nickname [用户昵称]
     * @param $headImage [用户头像]
     * @return array
     */
    public function updateUserInfo($uid, $nickname, $headImage)
    {
        return $this->client->updateUserInfo($uid, $nickname, $headImage);
    }


    /**
     * 组装聊天消息发送数据包结构
     * @param $fromUid
     * @param $toUid
     * @param $content
     * @param $content_type
     * @param $chat_type
     * @param $audio_time
     * @param $msg_type 0用户消息，1红线消息，2搭讪消息
     * @param $directly -false放入消息队列 true直接发送
     * @return bool
     */
    public function sendMsg($fromUid, $toUid, $content, $content_type = 1, $chat_type = 29, $audio_time = 0, $msg_type = 0, $ctime = 0, $directly = false)
    {
        try {
            $senderUser = User::find($fromUid);
            $senderUser = modelToArray($senderUser);
            if ($senderUser['sex'] == 1) {
                $uid = $fromUid;
                $anchor_id = $toUid;
            } else {
                $uid = $toUid;
                $anchor_id = $fromUid;
            }

            $sender = (new MessageAction())->formatUserInfo($senderUser); //$userModel->getMsgUserData($fromUid);
            if (isset($sender['m_id'])) unset($sender['m_id']);
            if (isset($sender['ip'])) unset($sender['ip']);
            if (isset($sender['service_id'])) unset($sender['service_id']);

            $from = $sender["from"];
            $version_code = $sender["version_code"];
            $channel = $sender["channel"];

            if (isset($sender['from'])) unset($sender['from']);
            if (isset($sender['version_code'])) unset($sender['version_code']);
            if (isset($sender['channel'])) unset($sender['channel']);

            $time = ($ctime > 0) ? $ctime : time();
            //$sync_sender = $sender['sex'] == 2 ? 1 : 0;
            $sync_sender = ($msg_type == 1) ? 0 : 1;
            if ($ctime > 0) {
                $sync_sender = 2; //接收端不显示
            }

            $msgData['closeness'] = ClosenessDao::read($uid, $anchor_id);
            $msgData['uid'] = (int)$fromUid;    //发送方
            $msgData['receive_uid'] = (int)$toUid;   //接收方
            $msgData['content'] = $content;
            $msgData['audio_time'] = $audio_time;
            // $msgData['ip'] = FunUtil::getClientIp();
            $msgData['from'] = (int)$from;
            $msgData['version_code'] = (int)$version_code;
            $msgData['ctime'] = $time;
            $msgData['w'] = $img_w ?? 0;
            $msgData['h'] = $img_h ?? 0;
            // $msgData['service_id'] = 0;
            $msgData['chat_type'] = $chat_type;
            $msgData['message_price'] = $chat_type == 5 ? '0.40' : ($chat_type == 3 ? '0.10' : '0');
            $msgData['message_id'] = md5(getMillisecond() . rand(1000, 9999));
            // $msgData['is_hello'] = 1;
            $msgData['sync_sender'] = $sync_sender;
            // $msgData['gid'] = 0;
            // $msgData['m_id'] = 0;
            $msgData['channel_number'] = $channel;  //渠道号
            $msgData['content_type'] = $content_type; //1文本消息，2语音消息，3图片消息
            $msgData['msg_type'] = $msg_type;
            $msgData['user_info'] = $sender;

            // 新人标识
            // $receiver = $userModel->find("`id`, `nickname`, `head_image`, `from`, `version_code`, `channel`, `last_login_ip`, `is_disturb`, `register_time`", "id = ?", [$toUid]);
            $receiver = User::query()->select(['id', 'nickname', 'head_image', 'from', 'version_code', 'channel', 'last_login_ip', 'is_disturb', 'register_time'])->where('id', $toUid)->first();
            $receiver = modelToArray($receiver);

            $msgData['to_is_new_user'] = ($receiver['register_time'] + 7 * 86400 >= time()) ? 1 : 0;
            $msgData['is_new_user'] = ($senderUser["register_time"] + 7 * 86400 >= time()) ? 1 : 0;

            if (isset($receiver['from'])) unset($receiver['from']);
            if (isset($receiver['version_code'])) unset($receiver['version_code']);
            if (isset($receiver['channel'])) unset($receiver['channel']);
            if (isset($receiver['last_login_ip'])) unset($receiver['last_login_ip']);
            if (isset($receiver['register_time'])) unset($receiver['register_time']);

            $msgData['receiver'] = $receiver;
            $msgData['is_red'] = 0;

            if (in_array($msgData['content_type'], array(4, 5))) {
                if (isset($msgData['call_data'])) {
                    $msgData['call_data'] = json_decode($msgData['call_data'], true);
                }
            } elseif ($msgData['content_type'] == 6) {
                $msgData['gift_data'] = json_decode($msgData['gift_data'], true);
            } elseif ($msgData['content_type'] == 7) {
                $msgData['demand_gift'] = json_decode($msgData['demand_gift'], true);
            } else {
                $msgData['content'] = htmlspecialchars($msgData['content']);
            }
            $msgData['distance'] = "";

            $msg[0] = $msgData;
            $message = json_encode(['event' => 'user_conn', 'msg' => $msg, 'desc' => '获取成功'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

            // return $this->putAttachMsgQueue($fromUid, $toUid, $message);

            // false放入消息队列 true直接发送
            return $directly ? $this->client->sendCustomMsg($fromUid, $toUid, $message) : PushMessageService::putYunXinCustomMsgQueue($fromUid, $toUid, $message);
        } catch (\Throwable $e) {
            LoggerUtil::write("send_msg", [
                "uid" => $fromUid,
                "message" => $e->getMessage(),
                "file" => $e->getFile(),
                "line" => $e->getLine(),
            ]);
            return false;
        }
    }


    /**
     * 批量发送系统消息
     * @param $message
     * @param string $package
     * @param int $sex
     */
    public function sendToAll($message, $package = "all", $sex = 0)
    {
        // 所有在线用户
        $uids = UserDao::getInstance()->getOnlineUids($sex);
        //审核环境的用户不发
        $aUids = UserDao::getInstance()->getAuditUidsEx();
        $uids = array_diff($uids, $aUids);

        // 未在线用户处理
        $msg = json_decode($message, true);
        if (isset($msg['msg']) && sizeof($msg['msg']) > 0 && isset($msg['msg'][0]['content']) && $msg['msg'][0]['content']) {
            $this->assist($sex, $msg['msg'][0]['content'], $package, $aUids);
        }

        // 排除非当前软件的用户
        if ($package !== "all") {
            // $uids = (new \lib\services\user\UserService())->exclude($uids, $package);
            $uids = User::query()->whereIn('id', $uids)->where('package', $package)->pluck('id')->toArray();
        }
        if (sizeof($uids) > 0) {
            PushMessageService::putYunXinBatchSendAttachMsgQueue($message, $uids);
        }
    }


    /**
     * 批量发送 飘窗消息
     * @param $event
     * @param $data
     */
    public function sendToAllRechargeNotice($event, $data)
    {
        $message = json_encode(compact("event", 'data'));
        $this->sendToAll($message, "all", 2);
    }


    /**
     * 用于注入 Fun::socket_client
     * @param $message
     */
    public function fastPush($message)
    {
        switch ($message["event"]) {
            //登录
            case "login":
                $this->login($message);
                break;
            //登出
            case "logout":
                $this->logout($message);
                break;
            //推送socket消息给聊天主播
            case "send":
                $this->send($message);
                break;
            //消息转发，不再通过mongo表记录
            case "send_message":
                $this->send_message($message);
                break;
            //新男性用户拒绝套路消息 v2.1.1 定义所有的用户
            case "new_user_reject":
                $this->new_user_reject($message);
                break;
            //通知
            case "notice":
                $this->notice($message);
                break;
            //聊天主播消息推送
            case "chat_hosting":
                $this->chat_hosting($message);
                break;
            //修改配置[系统推送]
            case "update_session":
                $this->update_session($message);
                break;
            //推送socket消息给聊天主播
            case "real_send":
                $this->real_send($message);
                break;
            //修改配置[系统推送]
            case "assistant":
                $this->assistant($message);
                break;
            //系统消息[系统推送]
            case "assistant_uid":
                $this->assistant_uid($message);
                break;
            //充值成功，转发给客户端
            case "pay_success":
                $this->pay_success($message);
                break;
            //心跳
            case "ping":
                $this->ping($message);
                break;
            //是否显示女神排行榜
            case "goddess_rank":
                $this->goddess_rank($message);
                break;
            ################以下未用到####################


            //发送语聊配置[系统推送]
            case "chat_config":
                $this->chat_config($message);
                break;
            //自定义登录[系统推送]
            case "custom_login":
                $this->custom_login($message);
                break;
            //自定义发送[系统推送]
            case "custom_send":
                $this->custom_send($message);
                break;

            //推送socket消息给聊天主播
            case "html_notice":
                $this->html_notice($message);
                break;
            //新男性用户是否获取托管消息、脚本消息的状态
            case "set_message_status":
                $this->set_message_status($message);
                break;
            //主播小视频点赞操作
            case "video_dianZan":
                $this->video_dianZan($message);
                break;
            case "send_room":
                $this->send_room($message);
                break;
            case "send_user":
                $this->send_user($message);
                break;

        }
    }


    /**
     * 是否显示女神排行榜
     * @param $message
     */
    public function goddess_rank($message)
    {
        $uids = UserDao::getInstance()->getOnlineUids(2);
        if (sizeof($uids) > 0) {
            PushMessageService::putYunXinBatchSendAttachMsgQueue($message, $uids);
        }
    }

    public function ping($message)
    {
        $uid = $message["uid"];
        $t = date('YmdH', time());
        $key = "user_pong_" . $t;
        $exist_value = RedisClient::getInstance()->hExists($key, $uid);
        if ($exist_value == 0) {
            RedisClient::getInstance()->hSet($key, $uid, 1);
        }
    }

    /**
     * Note - im登录触发
     * DateTime 2024/8/21 11:01
     * User Admin
     * @param $message
     */
    public function login($message)
    {
        $userInfo = UserDao::getInstance()->findUserInfoCache($message["uid"]);
        //重构在线用户的逻辑
        $this->setOnlineUid($message["uid"], $userInfo['sex']);
        //获取未读消息
        $this->sendLastMessage($message["uid"]);
        //开始统计时长
        $this->stOnline($userInfo, 1);
        //系统推送
        $this->stAssist($message["uid"]);

    }

    /**
     * im退出登录触发
     * @param $message
     */
    public function logout($message)
    {
        $uid = $message["uid"];
        $userInfo = UserDao::getInstance()->findUserInfoCache($uid);

        //设置下线用户
        $this->setOnlineUid($uid, $userInfo['sex'], 0, 'onClose');
        //结束统计时长
        $this->stOnline($userInfo, 2);
    }

    /**
     * 统计在线时长
     * @param $userInfo
     * @param $type //1=>上线 2=>下线
     */
    public function stOnline($userInfo, $type)
    {
        $type == 1 ? OnlineDao::getInstance()->insertData($userInfo['id']) : OnlineDao::getInstance()->closeData($userInfo['id']);
    }

    /**
     * 获取未发送的系统消息
     * @param $uid
     * @return array
     */
    public function stAssist($uid)
    {
        $mon = MongoDBClient::getInstance();
        $time = time();
        //查找上次拉取数据之后的数据
        $lastMsgWhere['uid'] = intval($uid);
        $lastMsgOption['limit'] = 1;
        $lastMsg = $mon->find('tb_assistant_last_list_ids_time', $lastMsgWhere, $lastMsgOption);
        $findMsgTime = $time - 86400 * 7;
        if (!empty($lastMsg) && isset($lastMsg[0]['last_time'])) {
            $lastMsgTime = $lastMsg[0]['last_time'];
            $findMsgTime = max($lastMsgTime, $findMsgTime);
        }
        $where['ctime']['$gt'] = $findMsgTime;
        $where['uid'] = intval($uid);
        $whereOption['sort'] = array('_id' => -1);
        $whereOption['limit'] = 100;
        $records = $mon->find('tb_assistant_last_list_ids', $where, $whereOption);

        foreach ($records as $record) {
            $msg = json_encode(array('event' => 'assistant', 'msg' => [$record], 'desc' => '获取成功'));
            PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, intval($uid), $msg);
        }
        $thisMsgModify['last_time'] = $time;
        $thisMsgModify = array_merge($lastMsgWhere, $thisMsgModify);
        $mon->update('tb_assistant_last_list_ids_time', $lastMsgWhere, $thisMsgModify, false, true);
    }

    /**
     * 获取当前用户未读的私信，并且返回
     * @param $uid
     */
    public function sendLastMessage($uid)
    {
        $lastMessage = UserChatV2Dao::getInstance()->getLastMessage($uid);
        if (!empty($lastMessage['data'])) {
            foreach ($lastMessage['data'] as $message) {
                $msg = json_encode(array('event' => 'user_conn', 'client_uid' => $uid, 'msg' => [$message], 'desc' => '获取成功'));
                PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $uid, $msg);
            }
        }
    }

    /**
     * 用户上下线触发
     * @param $uid
     * @param $sex
     * @param int $online
     * @param string $flag
     * @return bool
     */
    public function setOnlineUid($uid, $sex, int $online = 1, string $flag = '')
    {
        $sex = $sex == 1 ? 'man' : 'woman';

        if ($sex == "woman") {
            $redis = RedisClient::getInstance();
            if ($online == 1) {
                $rResult = $redis->sAdd("sys_online_anchor_uids", $uid);
            } else {
                $rResult = $redis->sRem("sys_online_anchor_uids", $uid);
            }
        } else {
            // 男用户登录成功直接加入代发消息队列
            //if ($online == 1) {
            //    (new RedisConn())->getConn()->lPush("queue:auto_greet2_exec_queue", json_encode(compact("uid")));
            //}
        }

        return UserDao::getInstance()->updateUserOnline($uid, $online);
    }

    public function video_dianZan($message)
    {

    }

    public function set_message_status($message)
    {
        if (isset($message['status'])) {
            $this->setMessageUidStatus($message['uid'], intval($message['status']));
        }
    }

    public function setMessageUidStatus($uid, $status = 1)
    {
        $messageUid = (array)MemcacheClient::getInstance()->get("message_uid_status");
        if ($status == 1) {
            if (!isset($messageUid) || !in_array($uid, $messageUid)) {
                $messageUid[] = $uid;
            }
        } else {
            if (!empty($messageUid)) {
                if (isset($messageUid[0])) unset($messageUid[0]);
                if (isset(array_flip($messageUid)[$uid])) unset($messageUid[array_flip($messageUid)[$uid]]);
            }
        }
        MemcacheClient::getInstance()->set("message_uid_status", $messageUid);
    }


    public function real_send($message)
    {
        if (!empty($message['data']) && isset($message['data']['user_id'])) {
            $this->sendMessage(intval($message['data']['user_id']));
            $message = json_encode(array('event' => 'message', 'msg' => $message['data'], 'desc' => '获取消息'));
            $this->sendToAll($message);
        }
    }

    public function custom_send($message)
    {
        if (isset($message['id']) && isset($message['sign']) && $message['sign'] == '3db333e17077913059799a30c8f80cad') {
            $onlineUid = UserDao::getInstance()->getOnlineUids(1);
            if (!empty($onlineUid) && in_array((int)$message['receive_uid'], $onlineUid)) {
                $this->sendMessage((int)$message['receive_uid']);
            }

            $onlineUid = UserDao::getInstance()->getOnlineUids(2);
            if (!empty($onlineUid) && in_array((int)$message['uid'], $onlineUid)) {
                $tarUserInfo = UserDao::getInstance()->findUserInfoCache((int)$message['receive_uid']);
                $format = (new MessageAction())->formatUserInfo($tarUserInfo);
                unset($message['id']);
                unset($message['sign']);
                unset($message['event']);
                $msg[0] = $message;
                $msg[0]['user_info'] = $format;
                $msg[0]['is_hello'] = 0;
                $msg[0]['sort_type'] = 0;
                // $this->putAttachMsgQueue($this->client->from, intval($message['uid']), json_encode(array('event' => 'user_conn', 'client_uid' => (int)$message['uid'], 'msg' => $msg, 'desc' => '获取成功')));
                $messageStr = json_encode(array('event' => 'user_conn', 'client_uid' => (int)$message['uid'], 'msg' => $msg, 'desc' => '获取成功'));
                PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, intval($message['uid']), $messageStr);
            }

        }
    }

    public function sendMessage($uid)
    {
        $lastMessage = UserChatV2Dao::getInstance()->getLastMessage($uid);
        if (!empty($lastMessage['data'])) {
            foreach ($lastMessage['data'] as $message) {
                $msg = json_encode(array('event' => 'user_conn', 'client_uid' => $uid, 'msg' => [$message], 'desc' => '获取成功'));
                // $this->putAttachMsgQueue($this->from, $uid, $msg);
                PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $uid, $msg);
            }
        }
    }

    /**
     * 保存系统消息至mongodb
     * @param $type
     * @param $content
     * @param string $package
     * @param array $audit_ids
     */
    public function assist($type, $content, string $package = 'all', array $audit_ids = [])
    {
        $Uids = UserDao::getInstance()->getOnlineUids(intval($type));

        $time = strtotime("-1 day");
        $where[] = ['status', '=', 0];
        $where[] = ['isdel', '=', 0];
        $where[] = ['login_time', '>', $time];

        // $where = '';
        if ($package != "all") {
            // $where = " and package='{$package}'";
            $where[] = ['package', '=', $package];
        }

        switch ($type) {
            case 1:
                // $ids = (new UserModel())->findAll('id', "sex = ? and isdel = 0 and status=0 and login_time>$time {$where}", array(1));
                $where[] = ['sex', '=', 1];
                $id_list = User::query()->where($where)->pluck('id')->toArray();
                break;
            case 2:
                // $ids = (new UserModel())->findAll('id', "sex = ? and isdel = 0 and status=0 and login_time>$time {$where}", array(2));
                $where[] = ['sex', '=', 2];
                $id_list = User::query()->where($where)->pluck('id')->toArray();
                break;
            default:
                // $ids = (new UserModel())->findAll('id', "id > ? and isdel = 0 and status=0 and login_time>$time {$where}", array(0));
                $where = ['id', '>', 0];
                $id_list = User::query()->where($where)->pluck('id')->toArray();
        }
        // $id_list = array_column($ids, 'id');
        if (!empty($id_list)) {
            $last_list_ids = array_diff($id_list, $Uids, $audit_ids);
            if (!empty($last_list_ids)) {
                foreach ($last_list_ids as $v) {
                    $this->newUser($v, $content);
                }
            }
        }
    }

    public function newUser($uid, $msg, $content_type = 0)
    {
        $insertData = array();
        $mon = MongoDBClient::getInstance();
        $insertData['uid'] = intval($uid);
        $insertData['content'] = $msg;
        $insertData['content_type'] = $content_type;
        $insertData['ctime'] = time();
        $mon->insert('tb_assistant_last_list_ids', $insertData);
    }

    public function custom_login($message)
    {
        if (isset($message['id']) && isset($message['sign']) && $message['sign'] == '3db333e17077913059799a30c8f80cad') {
            $uid = intval($message['id']);
            $messageBody = json_encode(array('event' => 'logout', 'msg' => array(), 'desc' => '强制退出'));
            // $this->putAttachMsgQueue($this->from, $uid, $messageBody);
            PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $uid, $messageBody);
        }
    }

    /**
     * 小秘书推送
     * @param $message
     */
    public function assistant($message)
    {
        // if (isset($message['data']['type']) && isset($message['data']['content'])) {
        //     $this->assist($message['data']['type'], $message['data']['content']);
        // }

        $new_message = json_encode(array('event' => 'assistant', 'msg' => array(0 => array('content' => $message['data']['content'], 'ctime' => time(), 'content_type' => $message['data']['content_type'])), 'desc' => '获取成功'));

        if ($message['uid'] > 0) {
            //审核环境的用户不发
            // $model = new UserModel();
            $inAudit = UserDao::getInstance()->inAudit($message['uid']);
            if (!$inAudit) {
                if (User::query()->where('id', $message['uid'])->value("online")) {
                    // $this->putBatchAttachMsgQueue($new_message, [intval($message['uid'])]);
                    PushMessageService::putYunXinBatchSendAttachMsgQueue($new_message, [intval($message['uid'])]);
                } else {
                    $this->newUser($message['uid'], $message['data']['content']);
                }
            }
        } else {
            $this->sendToAll($new_message, $message['data']['package'], intval($message['data']['type']));
        }
    }


    /**
     * 用户在线状态队列任务
     * @param $uid
     * @param $online 0-用户下线 1-用户上线 2-用户通话中 3-用户后台运行 4-用户勿扰
     * @param int $test
     * @return bool
     * @throws \Exception
     */
    public function user_online($uid, $online): bool
    {
        $user = User::where('id', $uid)->select(['id', 'is_disturb', 'sex', 'hide_call_status', 'nickname', 'head_image'])->first();
        $user = modelToArray($user);

        if ($user['sex'] == 1) {
            return true;
        }
        if ($online == 1) {
            if ($user['is_disturb'] == 1) {
                $online = 4;
            }
        } elseif ($online == 2 && $user['hide_call_status']) {
            $online = 1;
        }

        $onlineUserIds = UserDao::getInstance()->getOnlineUids($user['sex'] == 2 ? 1 : 2);
        $toUids = '';
        if (is_array($onlineUserIds)) {
            $toUids = implode(",", $onlineUserIds);
        }
        if (!empty($toUids)) {
            $message = json_encode([
                'event' => 'user_online',
                'msg' => ['uid' => $uid, 'online' => $online, 'nickname' => $user['nickname'], 'head_image' => $user['head_image']]
            ]);
            $fromUid = $uid;
            PushMessageService::putYunXinUserOnlineStatus($fromUid, $toUids, $message);
        } else {
            return false;
        }
        return true;

    }


    /**
     * 支付成功消息
     * @param $message
     */
    public function pay_success($message)
    {
        $userInfo = UserDao::getInstance()->findUserInfoCache($message["uid"]);
        $order = $this->getOrderInfo($message["uid"]);
        // $type = (isset($order) && $order['consume_type'] > 20) ? 2 : 1; // 1 vip 2 金币
        if (isset($order)) {
            if ($order['consume_type'] >= 7 && $order['consume_type'] < 50) {
                $type = 2;
            } elseif ($order['consume_type'] > 50) {
                $type = 1;
            } elseif (in_array($order['consume_type'], [0, 1])) {
                $type = 3;      // 3 购买微信
            } else {
                return true;
            }
        } else {
            return true;
        }
        PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $message["uid"], json_encode(array(
            'event' => 'pay_success',
            'client_uid' => $message["uid"],
            'msg' => [
                'gift_count' => $userInfo['gift_count'],
                'call_gold' => bcadd($userInfo['gift_count'] + $userInfo['recharge_send_count'], $userInfo['sys_send_count']),
                'order_info' => $order,
                'price' => (int)round($order['price'] * 100, 0),
                'type' => $type],
            'desc' => '获取成功'
        )));
    }


    /**
     * openinstall 效果点回传通知消息
     * @param $uid
     * @param $effect
     * @param $value
     */
    public function openinstallCallback($uid, $effect, $value)
    {
        PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $uid, json_encode([
            'event' => 'open_callback',
            'client_uid' => $uid,
            'msg' => [
                'effect' => $effect,
                'effect_value' => $value,
            ],
            'desc' => '获取成功'
        ]));
    }


    /**
     * 获取用户最新充值成功订单
     * @param $uid
     * @return array
     */
    public function getOrderInfo($uid)
    {
        $data = Order::query()->where('uid', $uid)
            ->where('pay_status', 1)
            ->where('notify_status', 1)
            ->orderBy('id', 'desc')
            ->first();
        return modelToArray($data);
        // return (new OrderModel())->find('*', "pay_status=1 and notify_status=1 and uid=? ", [$uid], ' id DESC');
    }

    /**
     * 发送语聊配置
     * @param $message
     */
    public function chat_config($message)
    {
        $new_message = json_encode(['event' => 'chat_config', 'chat_config' => $message['data']]);
        PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, intval($message['uid']), $new_message);
    }

    /**
     * 发送系统消息
     * @param $message
     */
    public function send($message)
    {
        if (!empty($message['data'])) {
            if (isset($message['data']['key']) && $message['data']['key'] == 'send_video_continus') {
                MemcacheClient::getInstance()->set("send_video_continus_id_" . $message['data']['msg']['video_id'], $message['data']['msg']['video_id']);
            } else if (isset($message['data']['key']) && $message['data']['key'] == 'send_duke_video_continus') {
                MemcacheClient::getInstance()->set("send_duke_video_continus_id_" . $message['data']['msg']['video_id'], $message['data']['msg']['video_id']);
            } else {
                $send_list = array_unique($message['data']);
                foreach ($send_list as $uid) {
                    $lastMessage = UserChatV2Dao::getInstance()->getLastMessage($uid);

                    logInfo("testBug", [$uid, $lastMessage]);
                    if (!empty($lastMessage['data'])) {
                        foreach ($lastMessage['data'] as $msg) {
                            $msg = json_encode(array('event' => 'user_conn', 'client_uid' => $uid, 'msg' => [$msg], 'desc' => '获取成功'));
                            // $this->putAttachMsgQueue(intval($message['uid']), $uid, $msg);
                            PushMessageService::putYunXinSendAttachMsgQueue($message['uid'], $uid, $msg);
                        }
                    }
                }
            }
        }
    }


    public function gagUserChat($uid = 0, $imei = '')
    {
        if (UserGagDao::getInstance()->checkGag($uid, 1)) {
            return true;
        }
        if (UserGagDao::getInstance()->checkGag($imei, 2)) {
            return true;
        }
        return false;
    }

    /**
     * 修改配置
     * @param $message
     */
    public function update_session($message)
    {
        $new_message = json_encode(array('event' => 'update_session', 'desc' => '修改配置'));
        // $this->putAttachMsgQueue($this->from, intval($message['uid']), $new_message);
        PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, intval($message['uid']), $new_message);
    }

    /**
     * 修改配置
     * @param $message
     */
    public function new_user_reject($message)
    {
        if (!empty($message['data']) && isset($message['data']['anchor_id'])) {
            $new_user_reject_data = (new AnchorScriptModel())->sendAnchor($message['uid'], $message['data']['anchor_id'], time() + 10);
            if (!empty($new_user_reject_data)) {
                $tarUserInfo = (new UserModel())->findUserInfoCache($new_user_reject_data['uid']);
                $format = (new MessageAction())->formatUserInfo($tarUserInfo);
                if (!empty($format) && $format['sex'] == 2) {
                    $video_data = (new AnchorVideoModel())->getOne($new_user_reject_data['uid']);
                    $format['video_url'] = !empty($video_data) ? $video_data['url'] : '';
                } else {
                    $format['video_url'] = '';
                }
                $new_user_reject_data = array_merge($new_user_reject_data, array('user_info' => $format));
                // $this->putAttachMsgQueue($this->from, $message['uid'], json_encode(array('event' => 'user_conn', 'msg' => array(0 => $new_user_reject_data), 'desc' => '获取成功')));
                $messageBody = json_encode(array('event' => 'user_conn', 'msg' => array(0 => $new_user_reject_data), 'desc' => '获取成功'));
                PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $message['uid'], $messageBody);
            }
        }
    }

    /**
     * 系统消息通知
     * @param $message
     */
    public function assistant_uid($message)
    {
        if (isset($message['uid']) && isset($message['data']['content'])) {
            $message['uid'] = intval($message['uid']);
            if (User::query()->where('id', $message['uid'])->value('online')) {
                $msg = json_encode(['event' => 'assistant',
                        'msg' => array(0 =>
                            array('content' => $message['data']['content'], 'ctime' => time(), 'content_type' => $message['data']['content_type'])
                        ),
                        'desc' => '获取成功'
                    ]
                );
                PushMessageService::putYunXinSendAttachMsgQueue(
                    $this->client->from,
                    $message['uid'],
                    $msg
                );
            } else {
                $this->newUser($message['uid'], $message['data']['content']);
            }
        }
    }

    /**
     * 发送消息给指定人员
     * @param $message
     */
    public function send_room($message)
    {
        if (!empty($message['data']) && isset($message['data']['uid_list']) && isset($message['data']['message'])) {
            $uids = $message['data']['uid_list'];
            $msg = $message['data']['message'];
            foreach ($uids as $uid) {
                // $this->putAttachMsgQueue($this->from, $uid, json_encode(['event' => 'room', 'msg' => $msg]));
                PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $uid, json_encode(['event' => 'room', 'msg' => $msg]));
            }
        }
    }

    /**
     * 发送消息给指定人员
     * @param $message
     */
    public function send_user($message)
    {
        if (!empty($message['data']) && isset($message['data']['uid_list']) && isset($message['data']['message'])) {
            $uids = $message['data']['uid_list'];
            $event_type = $message['data']['event_type'];
            $msg = $message['data']['message'];
            foreach ($uids as $uid) {
                // $this->putAttachMsgQueue($this->from, $uid, json_encode(['event' => $event_type, 'msg' => $msg]));
                PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $uid, json_encode(['event' => $event_type, 'msg' => $msg]));
            }
        }
    }

    /**
     * 通知
     * @param $message
     */
    public function notice($message)
    {
        if (!empty($message['data'])) {
            $this->sendToAll(json_encode(array('event' => 'notice', 'data' => $message['data'])));
        }
    }

    /**
     * 推送消息给聊天主播
     * @param $message
     */
    public function chat_hosting($message)
    {
        // $this->putAttachMsgQueue($this->from, $message['uid'], json_encode(['event' => 'chat_hosting', 'msg' => $message['data']]));
        PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $message['uid'], json_encode(['event' => 'chat_hosting', 'msg' => $message['data']]));
    }

    /**
     * 推送消息给聊天主播
     * @param $message
     */
    public function send_message($message)
    {
        if (!empty($message['data']) && isset($message['data']['uid_list']) && isset($message['data']['message'])) {
            $content = $message['data']['message'];
            $send_uid_list = $message['data']['uid_list'];

            $tarUserInfo = UserDao::getInstance()->findUserInfoCache($content['uid']);
            $format = (new MessageAction())->formatUserInfo($tarUserInfo);
            if (!empty($format) && $format['sex'] == 2) {
                $format['video_url'] = AnchorVideo::query()->where('anchor_id', $content['uid'])->value('url') ?? '';
            } else {
                $format['video_url'] = '';
            }
            $content['user_info'] = $format;

            if (in_array($content['content_type'], array(4, 5))) {
                if (isset($content['call_data'])) {
                    $content['call_data'] = json_decode($content['call_data'], true);
                }
            } elseif ($content['content_type'] == 6) {
                $content['gift_data'] = json_decode($content['gift_data'], true);
            } elseif ($content['content_type'] == 7) {
                $content['demand_gift'] = json_decode($content['demand_gift'], true);
            } else {
                $content['content'] = htmlspecialchars($content['content']);
            }
            $content['distance'] = "";
            $msg[0] = $content;
            $msg = json_encode(array('event' => 'user_conn', 'msg' => $msg, 'desc' => '获取成功'));
            foreach ($send_uid_list as $send_uid) {
                PushMessageService::putYunXinSendAttachMsgQueue($message['uid'], $send_uid, $msg);
                // $this->putAttachMsgQueue(intval($message['uid']), $uid, $msg);
            }
        }
    }

    /**
     * 推送消息给聊天主播
     * @param $message
     */
    public function html_notice($message)
    {
        if (!empty($message['data'])) {
            if (isset($message['data']['key']) && $message['data']['key'] == 'html_notice') {
                $this->putAttachMsgQueue($this->from, $message['uid'], json_encode(array('event' => 'html_notice', 'data' => $message['data'])));
            } else if (isset($message['data']['key']) && $message['data']['key'] == 'logout') {
                (new FiltrationModel())->setOnlineUid($message['uid'], $message['data']['msg']['game_id'], 0);
            } else if (isset($message['data']['key']) && $message['data']['key'] == 'refresh_hammer_num') {

                $this->putAttachMsgQueue($this->from, $message['uid'], json_encode(array('event' => 'html_notice', 'data' => $message['data'])));
            } else if (isset($message['data']['key']) && $message['data']['key'] == 'send') {
                $userInfo = (new UserModel())->findUserInfoCache($message['uid']);
                $game = (new ConfigRoomGameInfoModel())->getData(1001);
                if ((!empty($game) && $userInfo['sex'] == 1 && $userInfo['level'] >= $game['level']) || $userInfo['sex'] == 2) {
                    $content = $message['data']['msg']['content'];
                    $arr = array('msg' => array('uid' => $message['uid'], 'nickname' => $userInfo['nickname'], 'level' => (int)$userInfo['level'], 'sex' => (int)$userInfo['sex'], 'content' => $message['data']['msg']['content']), 'key' => 'chat_msg');
                    if (isset($message['data']['msg']['content']) && (mb_strlen(preg_replace('/\D/s', '', $content)) >= 6 || (new FiltrationModel())->isExistIllega($content, 1))) {

                        // $this->putAttachMsgQueue($this->from, $message['uid'], json_encode(array('event' => 'html_notice', 'data' => $arr)));
                        PushMessageService::putYunXinSendAttachMsgQueue($message['uid'], $message['uid'], json_encode(array('event' => 'html_notice', 'data' => $arr)));
                    } else {
                        $gameOnlineUids = Mem::get('im_game_online_uids_id_' . $message['data']['msg']['game_id']);
                        foreach ($gameOnlineUids as $v) {
                            // $this->putAttachMsgQueue($this->from, $v, json_encode(array('event' => 'html_notice', 'data' => $arr)));
                            PushMessageService::putYunXinSendAttachMsgQueue($this->client->from, $v, json_encode(array('event' => 'html_notice', 'data' => $arr)));
                        }
                    }
                }
            }
        }
    }

    /**
     * 用户登录登出事件记录查询
     * @param $uid
     * @return mixed|string
     */
    public function queryUserEvents($uid)
    {
        return $this->client->queryUserEvents($uid);
    }


}